﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web.UI.WebControls;
using ThangNM_LIB.DB;
using ThangNM_LIB.EO;
using ThangNM_LIB.FUNC;

namespace API
{
    public partial class ErrorUC : System.Web.UI.UserControl
    {
        //public AccessUI pContainer;
        public List<LogEO> lstLogEO
        {
            get { return (List<LogEO>)ViewState["lstLogEO"]; }
            set { ViewState["lstLogEO"] = value; }
        }

        public SortDirection directionState
        {
            get { return (ViewState["directionState"] == null ? SortDirection.Descending : (SortDirection)ViewState["directionState"]); }
            set { ViewState["directionState"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //pContainer = Page as AccessUI;
            Call_Msg(true, 0, null, null);
            //Title_FormUC1.setTitle(GetListConstants.getTableName(TableID_C.Error, TYPE.sName), funcButtonToolBar.LIST);
            if (!IsPostBack)
            {
                BindData_DropDownList();
                BindData_DropDownList_FILE();
            }
        }

        private void BindData_DropDownList()
        {
            try
            {
                ddlTableSplit.DataSource = (new ShareDAO.LogDAO()).Database_SelectAllTableName();
                ddlTableSplit.DataTextField = "Value";
                ddlTableSplit.DataValueField = "Value";
                ddlTableSplit.DataBind();
                BindData_List(null);
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx. FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        private void BindData_List(String sSortColumn)
        {
            try
            {
                grvLogs.Visible = false;
                btnDeleteItem.Enabled = true;
                btnDeleteAll.Enabled = true;
                if (String.IsNullOrEmpty(ddlTableSplit.SelectedValue))
                {
                    btnDeleteItem.Enabled = false;
                    btnDeleteAll.Enabled = false;
                    grvLogs.Visible = false;
                    lblRowCount.Visible = false;
                    return;
                }
                else if (StringEx.Equals(ddlTableSplit.SelectedValue, "tblLog") || StringEx.Equals(ddlTableSplit.SelectedValue, "tblLogOther"))
                {
                    btnDeleteItem.Text = "Xóa dữ liệu bảng log này";
                    btnDeleteItem.OnClientClick = String.Format("return confirm('Bạn có muốn xóa dữ liệu bảng log [{0}] không?');", ddlTableSplit.SelectedValue);
                }
                else
                {
                    btnDeleteItem.Text = "Xóa bảng log này";
                    btnDeleteItem.OnClientClick = String.Format("return confirm('Bạn có muốn xóa bảng log [{0}] không?');", ddlTableSplit.SelectedValue);
                }
                DataTable dt = new ShareDAO.LogDAO().Log_SelectBy_TableName(ddlTableSplit.SelectedValue);
                DataView dv = dt.DefaultView;
                if (!String.IsNullOrEmpty(sSortColumn))
                    dv.Sort = sSortColumn;
                else
                    dv.Sort = "[iLogID] DESC";
                dt = dv.ToTable();
                if (dt.Rows.Count > 0)
                {
                    grvLogs.Visible = true;
                    lblRowCount.Visible = true;
                    grvLogs.DataSource = dt;
                    grvLogs.DataBind();
                    lblRowCount.Text = MessagesEx.Tong_So_Ban_Ghi + dt.Rows.Count;
                    return;
                }
                grvLogs.DataSource = null;
                grvLogs.DataBind();
                lblRowCount.Text = MessagesEx.Khong_Thoa_Man_Dieu_Kien_Tim_Kiem;
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void ddlTableSplit_SelectedIndexChanged(object sender, EventArgs e)
        {
            BindData_List(null);
        }

        protected void grvLogs_Sorting(object sender, System.Web.UI.WebControls.GridViewSortEventArgs e)
        {
            if (directionState == SortDirection.Ascending)
            {
                directionState = SortDirection.Descending;
                BindData_List("[" + e.SortExpression + "]" + " DESC");
            }
            else
            {
                directionState = SortDirection.Ascending;
                BindData_List("[" + e.SortExpression + "]" + " ASC");
            }
        }

        protected void grvLogs_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvLogs.PageIndex = e.NewPageIndex;
            BindData_List(null);
        }

        protected void Call_Msg(Boolean isClearMsg, Int16 iType, string strMsg, String strMsgFull = null)
        {
            //if (pContainer != null)
            //{
            if (isClearMsg)
            {
                lblMsg.Text = "";
            }
            else
            {
                lblMsg.Text = strMsg;
            }
            //}
        }

        protected void btnLoadTable_Click(object sender, EventArgs e)
        {
            BindData_List(null);
        }

        protected void btnDeleteItem_Click(object sender, EventArgs e)
        {
            try
            {
                Boolean bRet = false;
                if (StringEx.Equals(ddlTableSplit.SelectedValue, "tblLog") || StringEx.Equals(ddlTableSplit.SelectedValue, "tblLogOther"))
                    bRet = (new ShareDAO.LogDAO()).Log_DeleteDataTable(ddlTableSplit.SelectedValue);
                else
                    bRet = (new ShareDAO.LogDAO()).Log_DropTable(ddlTableSplit.SelectedValue);
                if (bRet)
                    Call_Msg(false, ConstEx.FunctionSetMsg.SUCCESS, MessagesEx.Xoa_Thanh_Cong_Default);
                else
                    Call_Msg(false, ConstEx.FunctionSetMsg.WARNING, MessagesEx.Xoa_That_Bai_Default);
                BindData_DropDownList();
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void btnDeleteAll_Click(object sender, EventArgs e)
        {
            try
            {
                DataTable dt = (new ShareDAO.LogDAO()).Database_SelectAllTableName();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        String TableName = Convert.ToString(dr["Value"]);
                        if (StringEx.Equals(TableName, "tblLog") || StringEx.Equals(TableName, "tblLogOther"))
                            (new ShareDAO.LogDAO()).Log_DeleteDataTable(TableName);
                        else
                            (new ShareDAO.LogDAO()).Log_DropTable(TableName);
                    }
                    BindData_DropDownList();
                }
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }





        protected void BindData_Grid()
        {
            grvError.DataSource = lstLogEO;
            grvError.DataBind();
            lblTotal.Text = String.Format("Tổng số bản ghi: {0}", lstLogEO.Count);
        }

        private void BindData_DropDownList_FILE()
        {
            try
            {
                String strPath = System.Configuration.ConfigurationManager.AppSettings["RawUrl_RootPath"] + "Logs\\";
                ddlFileError.DataSource = Folder_File.getListFileInFolder(strPath);
                ddlFileError.DataTextField = "Value";
                ddlFileError.DataValueField = "Key";
                ddlFileError.DataBind();
                getData();
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void getData()
        {
            try
            {
                String sPath = ddlFileError.SelectedValue;
                String sContent = "";
                lstLogEO = (new Logs()).ReadLog_From_File(sPath, ref sContent);
                txtContent.Text = sContent;
                BindData_Grid();
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void btnLoad_Click(object sender, EventArgs e)
        {
            getData();
        }

        protected void btnClearItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(ddlFileError.SelectedValue))
                {
                    lstLogEO.Clear();
                    txtContent.Text = "";
                    File.Delete(ddlFileError.SelectedValue);
                    BindData_DropDownList_FILE();
                }
            }
            catch (Exception ex)
            {
                Call_Msg(false, ConstEx.FunctionSetMsg.ERROR, ex.Message, ex.ToString());
            }
        }

        protected void btnMoveItem_Click(object sender, EventArgs e)
        {
            String sTemp = (new Logs()).WriteLog_File_To_DB(false, ddlFileError.SelectedValue);
            if (String.IsNullOrEmpty(sTemp))
                Call_Msg(false, ConstEx.FunctionSetMsg.SUCCESS, String.Format("Chuyển file log [{0}] vào DB thành công.", ddlFileError.SelectedValue));
            else
                Call_Msg(false, ConstEx.FunctionSetMsg.WARNING, String.Format("Chuyển file log [{0}] vào DB thất bại.<BR />{1}", ddlFileError.SelectedValue, sTemp));
            BindData_DropDownList_FILE();
        }

        protected void btnMoveAll_Click(object sender, EventArgs e)
        {
            String sTemp = (new Logs()).WriteLog_File_To_DB(false, null);
            if (String.IsNullOrEmpty(sTemp))
                Call_Msg(false, ConstEx.FunctionSetMsg.SUCCESS, String.Format("Chuyển tất cả các file vào DB thành công."));
            else
                Call_Msg(false, ConstEx.FunctionSetMsg.WARNING, String.Format("Chuyển tất cả các file vào DB thất bại.<BR />{0}", sTemp));
            BindData_DropDownList_FILE();
        }

        protected void grvError_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            grvError.PageIndex = e.NewPageIndex;
            BindData_Grid();
        }

        protected void ddlFileError_SelectedIndexChanged(object sender, EventArgs e)
        {
            getData();
        }
    }
}